﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Common;
using Controllers.Extend;
using Controllers.Filter;
using Model.Sys.Config;
using ViewModel;

namespace Controllers.Areas.Department.Controllers
{
    public class ManagerController : UserBaseController
    {
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            cookieName = CookieConfig.UserInfoLoginCookieName;
            base.OnAuthorization(filterContext);

            if (loginUser == null)
            {
                if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new JsonResult()
                    {
                        ContentEncoding = Encoding.UTF8,
                        Data = new ResultModel
                        {
                            Pass = false,
                            Msg = "对不起，您的身份验证过时，请重新登录。"
                        },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
                }
                else
                {
                    filterContext.Result = new ContentResult() { Content = "<script>alert('对不起，您的身份验证过时，请重新登录。');top.location='/Login/Index';</script>" };
                }
            }
        }

        /// <summary>
        /// 部门管理的列表页面
        /// </summary>
        /// <returns></returns>
        [Power(PowerId = "01000400")]
        public ActionResult Index()
        {
            ViewData["PowerId"] = "01000400";
            return View();
        }

        /// <summary>
        /// 部门管理的列表页面的列表查询
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public ActionResult Search(DataTable dt)
        {
            int total;
            List<Model.Database.Department> treeSortPowerList = new List<Model.Database.Department>();

            IQueryable<Model.Database.Department> departmentIq = CurrentBllSession.DepartmentBll.GetIQueryable();
            total = departmentIq.Count();
            List<Model.Database.Department> departmentList = departmentIq.ToList();
            TreeSortList(departmentList, treeSortPowerList, "0");
            dt.recordsTotal = total;
            dt.recordsFiltered = total;
            dt.data = treeSortPowerList;

            return Json(dt);
        }

        /// <summary>
        /// 增加部门页面
        /// </summary>
        /// <returns></returns>
        [Power(PowerId = "01000401")]
        public ActionResult Add()
        {
            return View();
        }

        /// <summary>
        /// 增加部门页面的树状部门
        /// </summary>
        /// <returns></returns>
        public ActionResult TreeList(string type)
        {
            IQueryable<Model.Database.Department> departmentIq = CurrentBllSession.DepartmentBll.GetIQueryable();
            List<Model.Database.Department> departmentList = departmentIq.ToList();
            List<ZTreeModel> treeList = MakeTreeList(departmentList);
            if (!string.IsNullOrEmpty(type) && type.Equals("userChoose")) //用户选择部门
            {
                treeList.Insert(0, new ZTreeModel() {id = "0", name = "请选择"});
            }
            else
            {
                treeList.Insert(0, new ZTreeModel() { id = "0", name = "父级" });
            }
            

            return Json(treeList);
        }

        /// <summary>
        /// 部门增加页面的提交
        /// </summary>
        /// <param name="pmDepartment"></param>
        /// <returns></returns>
        public ActionResult AddSubmit(Model.Database.Department pmDepartment)
        {
            ResultModel rm = new ResultModel();
            string[] roleIdArr = null;

            if (Request["id"] != null)
            {
                roleIdArr = Request["id"].Split(',');
            }
            if ((!string.IsNullOrEmpty(pmDepartment.ParentId)) && (!string.IsNullOrEmpty(pmDepartment.DepartmentName)) )
            {
                Model.Database.Department department = pmDepartment;

                department.DepartmentId = StringHelper.GetGuidString();
                department.ParentId = department.ParentId.Split(',').FirstOrDefault();
                List<Model.Database.Role> roleList = new List<Model.Database.Role>();
                if (roleIdArr != null) { roleList = CurrentBllSession.RoleBll.GetRoleListByIdArr(roleIdArr); }
                department.Roles = roleList;
                if (!department.Sort.HasValue)
                {
                    department.Sort = MakeSort(department.ParentId);
                }
                department.AddTime = DateTime.Now;
                CurrentBllSession.DepartmentBll.AddDepartmentAndDepartment_Role(department);
                rm.Pass = true;
                rm.Msg = "添加成功";
            }
            else
            {
                rm.Pass = false;
                rm.Msg = "请填写部门名，父级部门";
            }

            return Json(rm);
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="idArrStr"></param>
        /// <returns></returns>
        [Power(PowerId = "01000402")]
        public ActionResult Delete(string idArrStr)
        {
            ResultModel rm = new ResultModel();

            string[] idArr = idArrStr.Split(',');
            CurrentBllSession.DepartmentBll.ListDelete(idArr);
            rm.Pass = true;
            rm.Msg = "删除成功";

            return Json(rm);
        }

        /// <summary>
        /// 修改部门
        /// </summary>
        /// <returns></returns>
        [Power(PowerId = "01000403")]
        public ActionResult Edit(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                VMDepartment vmDepartment=new VMDepartment();

                Model.Database.Department department = CurrentBllSession.DepartmentBll.GetEntity(id);
                string rolesName = CurrentBllSession.DepartmentBll.GetRoleName(id);
                string roleIds = CurrentBllSession.DepartmentBll.GetRoleIds(id);
                vmDepartment.Department = department;
                vmDepartment.RolesName = rolesName;
                vmDepartment.RoleIds = roleIds;

                return View(vmDepartment);
            }
            else
            {
                return Content("id参数无效");
            }
        }

        /// <summary>
        /// 修改部门提交
        /// </summary>
        /// <param name="pmDepartment"></param>
        /// <returns></returns>
        public ActionResult EditSubmit(Model.Database.Department pmDepartment)
        {
            ResultModel rm = new ResultModel();
            string[] roleIdArr = null;

            if (Request["id"] != null)
            {
                roleIdArr = Request["id"].Split(',');
            }
            if (!string.IsNullOrEmpty(pmDepartment.DepartmentName))
            {
                Model.Database.Department departmentOld = CurrentBllSession.DepartmentBll.GetEntity(pmDepartment.DepartmentId);

                departmentOld.DepartmentName = pmDepartment.DepartmentName;
                departmentOld.Description = pmDepartment.Description;
                if (pmDepartment.Sort.HasValue) { departmentOld.Sort=pmDepartment.Sort;}
                departmentOld.Roles = CurrentBllSession.DepartmentBll.GetRole(departmentOld.DepartmentId);
                List<Model.Database.Role> newRoleList = new List<Model.Database.Role>();
                if (roleIdArr != null) { newRoleList = CurrentBllSession.RoleBll.GetRoleListByIdArr(roleIdArr); }
                departmentOld.Roles = newRoleList;
                departmentOld.ModifyTime = DateTime.Now;
                CurrentBllSession.DepartmentBll.UpdateDepartmentAndDepartment_Role(departmentOld);
                rm.Pass = true;
                rm.Msg = "保存成功";
            }
            else
            {
                rm.Pass = false;
                rm.Msg = "请填写部门名臣";
            }

            return Json(rm);
        }

        /// <summary>
        /// 查看部门
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Power(PowerId = "01000404")]
        public ActionResult View(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                VMDepartment vmDepartment=new VMDepartment();

                Model.Database.Department department = CurrentBllSession.DepartmentBll.GetEntity(id);
                string rolesName = CurrentBllSession.DepartmentBll.GetRoleName(id);
                vmDepartment.Department = department;
                vmDepartment.RolesName = rolesName;

                return View(vmDepartment);
            }
            else
            {
                return Content("id参数无效");
            }
        }



        #region 私有方法

        /// <summary>
        /// 制作排序Sort
        /// </summary>
        private int MakeSort(string parentId)
        {
            int sort = 1;

            Model.Database.Department sameLevelNewestDepartment = CurrentBllSession.DepartmentBll.GetIQueryable()
                                                .Where(a => a.ParentId == parentId)
                                                .OrderByDescending(a => a.Sort)
                                                .FirstOrDefault();
            if (sameLevelNewestDepartment != null)
            {
                if (sameLevelNewestDepartment.Sort.HasValue)
                {
                    sort = sameLevelNewestDepartment.Sort.Value + 1;
                }
            }

            return sort;
        }

        /// <summary>
        /// 制作树状集合
        /// </summary>
        private List<ZTreeModel> MakeTreeList(List<Model.Database.Department> departmentList)
        {
            List<Model.Database.Department> treeSortList = new List<Model.Database.Department>();
            List<ZTreeModel> treeList = new List<ZTreeModel>();

            TreeSortList(departmentList, treeSortList, "0");
            foreach (var department in treeSortList)
            {
                ZTreeModel menu = new ZTreeModel() { id = department.DepartmentId, pId = department.ParentId, name = department.DepartmentName };
                treeList.Add(menu);
            }

            return treeList;
        }

        /// <summary>
        /// 树状排序集合（递归）
        /// </summary>
        private void TreeSortList(List<Model.Database.Department> departmentList, List<Model.Database.Department> treeSortDepartmentList, string parentId)
        {
            foreach (var department in departmentList.Where(a=>a.ParentId == parentId).OrderBy(a => a.Sort))//部门
            {
                treeSortDepartmentList.Add(department);
               
                TreeSortList(departmentList, treeSortDepartmentList, department.DepartmentId);
            }
        }

        #endregion
    }
}
